package com.wei.common.utils;

import lombok.SneakyThrows;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.apache.zookeeper.CreateMode;

import java.io.*;
import java.util.Properties;
import java.util.Set;

/**
 * 在运行seata之前需要运行下这个config
 * 或者执行(未验证过)
 * zk-config.sh -h localhost -p 2181 -z "/Users/zhangchenghui/zookeeper-3.4.14
 * @author weichuanyuan
 * @version 1.0
 * @date 2021/8/29 13:42
 */
public class InitSeataRegisterCenter {

    private static volatile ZkClient zkClient;

    private static String zkUrl = "192.168.62.147:2181";

    public static void main(String[] args) {
        if (zkClient == null) {
            zkClient = new ZkClient(zkUrl, 8000, 8000);
            zkClient.setZkSerializer(new ZkSerializer() {

                @SneakyThrows
                @Override
                public byte[] serialize(Object o) {
                        return String.valueOf(o).getBytes("UTF8");
                }

                @SneakyThrows
                @Override
                public Object deserialize(byte[] bytes) {
                    return new String(bytes, "UTF8");
                }
            });
        }
        if (!zkClient.exists("/seata")) {
            zkClient.createPersistent("/seata", true);
        }
        //获取key对应的value值
        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        // 使用properties对象加载输入流
        try {
            File file=new File("E:\\JavaProject\\springcloud-alibaba\\springcloud-alibaba-common\\src\\main\\resources\\config.txt");
            InputStream in = new FileInputStream(file);
            properties.load(in);
            Set<Object> keys = properties.keySet();
            for (Object key : keys) {
                putConfig(key.toString(), properties.get(key).toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param dataId
     * @param content
     * @return
     */
    public static boolean putConfig(final String dataId, final String content) {
        Boolean flag = false;
        String path = "/seata/" + dataId;
        if (!zkClient.exists(path)) {
            zkClient.create(path, content, CreateMode.PERSISTENT);
            flag = true;
        } else {
            zkClient.writeData(path, content);
            flag = true;
        }
        return flag;
    }
}
